import React from 'react';
import { Table, Input, InputNumber, Popconfirm, Form, Button, message } from 'antd';
import { DividerContainer, Icon } from '@/molecules';
import { isArray } from 'lodash';
import EvaluationItemTable from './EvaluationItemTable';
import styles from './index.less';

const EditableContext = React.createContext();

const EditItem = props => {
    const { editing, dataIndex, title, record, index, children, gradeList, ...restProps } = props;
    const context = React.useContext(EditableContext);
    const { form } = context;
    const { getFieldDecorator } = form;

    const getItem = () => {
        if (dataIndex === 'content') {
            const { content } = record;
            return <EvaluationItemTable form={form} dataSource={content || []} />;
        }
        if (dataIndex === 'weight') {
            return (
                <Form.Item style={{ margin: 0 }}>
                    {getFieldDecorator(dataIndex, {
                        rules: [
                            {
                                required: true,
                                message: '请输入权重占比'
                            }
                        ],
                        initialValue: record && record[dataIndex]
                    })(
                        <InputNumber
                            placeholder="请输入权重占比"
                            maxLength={4}
                            precision={0}
                            min={0}
                            max={100}
                            formatter={value => `${value}%`}
                            style={{ marginRight: 4 }}
                        />
                    )}
                </Form.Item>
            );
        }

        return (
            <Form.Item style={{ margin: '-10px 0 0' }}>
                {getFieldDecorator(dataIndex, {
                    rules: [
                        {
                            required: true,
                            message: `请输入${title}`,
                            whitespace: true
                        }
                    ],
                    initialValue: (record && record[dataIndex]) || ''
                })(
                    <Input.TextArea
                        placeholder={`请输入${title}`}
                        autoSize={{ minRows: 1, maxRows: 3 }}
                        maxLength={200}
                        autoFocus
                    />
                )}
            </Form.Item>
        );
    };

    const renderCell = () => {
        if (editing) {
            return <td {...restProps}>{getItem()}</td>;
        }

        return <td {...restProps}>{children}</td>;
    };

    return <EditableContext.Consumer>{renderCell}</EditableContext.Consumer>;
};

const EvaluationTable = ({ form: tempForm, dataSource, weightError = false, onChange, onEditing }) => {
    const [data, setData] = React.useState(dataSource || []);
    const [editingKey, setEditingKey] = React.useState('');

    const isEditing = record => record.id === editingKey;

    React.useEffect(() => {
        if (onChange) {
            onChange(data);
        }
    }, [data]);

    React.useEffect(() => {
        if (onEditing) {
            onEditing(editingKey);
        }
    }, [editingKey]);

    React.useEffect(() => {
        if (!dataSource || JSON.stringify(dataSource) === JSON.stringify(data)) {
            return;
        }
        setData(dataSource);
    }, [dataSource]);

    const getFinalItem = values => {
        const tempArr = [];
        [5, 4, 3, 2, 1].forEach(item => {
            const label = values?.[`label${item}`]?.trim() || '';
            if (label) {
                tempArr.push(item);
            }
        });

        return tempArr.map(item => ({
            value: item,
            label: values?.[`label${item}`]
        }));
    };

    const handleSave = (form, key) => {
        tempForm.validateFields((error, row) => {
            if (error) {
                return;
            }
            const newData = [...data];
            const index = newData.findIndex(item => key === item.id);
            if (index > -1) {
                const item = newData[index];
                const { project, weight } = row;
                const content = getFinalItem(row);
                if (content && content.length > 0) {
                    newData.splice(index, 1, {
                        ...item,
                        project,
                        weight,
                        content
                    });
                } else {
                    message.error('请添加至少一项评分标准');
                    return;
                }
            }
            setData(newData);
            setEditingKey('');
        });
    };

    const handleCancel = key => {
        const newData = [...data];
        const index = newData.findIndex(item => key === item.id);
        if (newData[index].project) {
            setEditingKey('');
        } else {
            newData.splice(index, 1);
            setData(newData);
            setEditingKey('');
        }
    };

    const handleEdit = key => {
        setEditingKey(key);
    };

    const handleDelete = key => {
        const newData = [...data];
        const index = newData.findIndex(item => key === item.id);
        if (index > -1) {
            newData.splice(index, 1);
        }
        setData(newData);
        setEditingKey('');
    };

    const handleAdd = () => {
        const newData = [...data];
        const tempKey = new Date().getTime();
        newData.push({
            id: tempKey,
            project: '',
            content: ''
        });
        setData(newData);
        setEditingKey(tempKey);
    };

    const columns = [
        {
            title: '评估项目',
            dataIndex: 'project',
            width: '15%',
            editable: true
        },
        {
            title: <span style={{ color: weightError ? '#f5222d' : '' }}>权重占比</span>,
            dataIndex: 'weight',
            width: 60,
            editable: true,
            render: text => `${text}%`
        },
        {
            title: (
                <div
                    style={{
                        position: 'absolute',
                        top: 0,
                        bottom: 0,
                        left: 16,
                        right: 0,
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center'
                    }}
                >
                    <div>评估标准</div>
                    <div
                        style={{
                            display: 'flex',
                            padding: 16,
                            alignItems: 'center',
                            width: 88,
                            height: '100%',
                            borderLeft: '1px solid #e8e8e8'
                        }}
                    >
                        得分
                    </div>
                </div>
            ),
            className: styles.headCol,
            dataIndex: 'content',
            // width: '60%',
            editable: true,
            render: text => {
                if (isArray(text) && text.length > 0) {
                    const block = text?.map((item, index) => (
                        <div
                            key={item.value}
                            style={{
                                flex: 1,
                                flexShrink: 0,
                                flexBasis: 'auto',
                                position: 'relative',
                                padding: '16px 104px 16px 16px',
                                display: 'flex',
                                alignItems: 'center',
                                wordBreak: 'break-all',
                                whiteSpace: 'pre-wrap',
                                borderBottom: index < text.length - 1 ? '1px solid #e8e8e8' : ''
                            }}
                        >
                            {item.label}
                            <div
                                style={{
                                    position: 'absolute',
                                    top: 0,
                                    right: 0,
                                    height: '100%',
                                    padding: 16,
                                    display: 'flex',
                                    alignItems: 'center',
                                    width: 88,
                                    borderLeft: '1px solid #e8e8e8'
                                }}
                            >
                                {item.value}
                            </div>
                        </div>
                    ));
                    return (
                        <>
                            <div
                                style={{
                                    display: 'flex',
                                    flexDirection: 'column',
                                    opacity: 0
                                }}
                            >
                                {block}
                            </div>
                            <div
                                style={{
                                    display: 'flex',
                                    flexDirection: 'column',
                                    position: 'absolute',
                                    top: 0,
                                    bottom: 0,
                                    left: 0,
                                    right: 0
                                }}
                            >
                                {block}
                            </div>
                        </>
                    );
                }
                return '';
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 100,
            render: (text, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <DividerContainer>
                        <EditableContext.Consumer>
                            {form => <Icon title="保存" type="confirm_o" onClick={() => handleSave(form, record.id)} />}
                        </EditableContext.Consumer>
                        <Icon title="取消" type="cancel_o" onClick={() => handleCancel(record.id)} />
                    </DividerContainer>
                ) : (
                    <DividerContainer>
                        <Icon
                            title="编辑"
                            disabled={editingKey !== ''}
                            type="listfunction_edit_icon_default"
                            onClick={() => handleEdit(record.id)}
                        />
                        <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
                            <Icon
                                title="删除"
                                disabled={editingKey !== ''}
                                type="listfunction_delete_icon_default"
                                onClick={() => {}}
                            />
                        </Popconfirm>
                    </DividerContainer>
                );
            }
        }
    ];

    const realColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record)
            })
        };
    });

    const components = {
        body: {
            cell: EditItem
        }
    };

    return (
        <EditableContext.Provider value={{ form: tempForm }}>
            <Table
                rowKey="id"
                bordered
                components={components}
                dataSource={data}
                columns={realColumns}
                rowClassName={styles.editableRow}
                pagination={false}
            />
            <Button
                type="dashed"
                icon="plus"
                block
                disabled={editingKey !== '' || data?.length >= 20}
                style={{ marginTop: 16 }}
                onClick={handleAdd}
            >
                新增评估项
            </Button>
        </EditableContext.Provider>
    );
};

export default Form.create()(EvaluationTable);
